<?php

namespace Tbf\Component\Arrays\Tests;

use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Yaml\Yaml;
use Tbf\Component\Arrays\ArrayFunction;

class ArrayFunctionTest extends \PHPUnit_Framework_TestCase
{
    public function testRekeyById()
    {
        $a = array(
            array('id'=>'a','a'=>'b'),
            array('id'=>'b','a'=>'c'),
        );
        $output = ArrayFunction::reKeyById($a);
        $expect = array(
            'a'=>array('id'=>'a','a'=>'b'),
            'b'=>array('id'=>'b','a'=>'c'),
        );
        $this->assertEquals($expect,$output);
    }
    public function testFirstValue(){
        $a = array(
            'first',
            'second'
        );
        $this->assertEquals('first',ArrayFunction::firstValue($a));

        $a = array(
            'a'=>'first1',
            'second2'
        );
        $this->assertEquals('first1',ArrayFunction::firstValue($a));

        $a = new ArrayCollection(array(
            'a'=>'first1',
            'second2'
        ));
        $this->assertEquals('first1',ArrayFunction::firstValue($a));
    }
    public function testCheckParameterExistAndScalar(){
        $a = array(
            'a'=>'s',
            'b'=>array()
        );
        $this->assertTrue(ArrayFunction::checkParameterExistAndScalar($a,array('a','b'))!==null);

        $a = array(
            'a'=>'s',
            'c'=>1,
            'd'=>1.1,
            'b'=>array()
        );
        $this->assertTrue(ArrayFunction::checkParameterExistAndScalar($a,array('a','c','d'))===null);

        $a = array(
            'a'=>'s',
            'b'=>null
        );
        $this->assertTrue(ArrayFunction::checkParameterExistAndScalar($a,array('a','b'))!==null);

        $a = array(
            'a'=>'s',
            'b'=>new \stdClass()
        );
        $this->assertTrue(ArrayFunction::checkParameterExistAndScalar($a,array('a','b'))!==null);
    }
    public function testLevel2KeyTran(){
        $a = array(
            array('a'=>1,'b'=>2),
            array('a'=>2)
        );
        $table = array('b'=>'d','a'=>'c');
        $this->assertEquals(array(
            array('d'=>2,'c'=>1),
            array('c'=>2)
        ),ArrayFunction::level2KeyTran($a,$table));
    }
    public function testInTurnFlatLevel2Array(){
        $data = Yaml::parse(<<<'YML'
- ['a','b','c','h','l', [1,2]]
- ['e','d','f']
YML
);
        $expect = Yaml::parse(<<<'YML'
['a','e','b','d','c','f','h','l',[1,2]]
YML
        );
        $this->assertEquals($expect,ArrayFunction::inTurnFlatLevel2Array($data));
    }
}
